<template>
  <view class="page-container">
    <!-- 搜索栏 -->
    <SearchBar @clickSearch="goToSearch" />
    
    <!-- 分类+商品区 -->
    <view class="main-content">
      <!-- 左侧分类 -->
      <scroll-view 
        scroll-y 
        class="category-list"
        :style="{height: scrollHeight + 'px'}"
      >
        <view 
          v-for="(item, index) in categories" 
          :key="item.id"
          class="category-item"
          :class="{active: activeCategoryId === item.id}"
          @click="switchCategory(item.id)"
        >
          {{ item.name }}
        </view>
      </scroll-view>

      <!-- 右侧商品 -->
      <scroll-view 
        scroll-y 
        class="goods-list"
        :style="{height: scrollHeight + 'px'}"
        @scrolltolower="loadMore"
      >
        <view class="goods-grid">
          <GoodsItem 
            v-for="goods in goodsList" 
            :key="goods.id"
            :goods="{
              id: goods.id,
              name: goods.name,
              price: goods.price,
              sales: goods.sales,
              thumb: goods.thumbUrl
            }"
            @click="goToDetail(goods.id)"
          />
        </view>
        <uni-load-more :status="loadStatus" />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import SearchBar from '@/pages/shop/components/SearchBar.vue'
import GoodsItem from '@/pages/shop/components/GoodsItem.vue'

// 响应式数据
const activeCategoryId = ref(null)
const categories = ref([])
const goodsList = ref([])
const scrollHeight = ref(0)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})
const loadStatus = ref('more')

// 获取分类数据
const fetchCategories = async () => {
  try {
    const { data } = await uni.request({
      url: 'http://localhost:8088/api/mall/categories',
      method: 'GET'
    })
    
    if (data?.code === 200) {
      categories.value = data.data
      if (categories.value.length > 0) {
        activeCategoryId.value = categories.value[0].id
        fetchGoods(true)
      }
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    uni.showToast({ title: '分类加载失败', icon: 'none' })
  }
}

// 获取商品数据
const fetchGoods = async (reset = false) => {
  if (!activeCategoryId.value) return
  
  try {
    loadStatus.value = 'loading'
    const currentPage = reset ? 1 : pagination.value.current
    
    const { data } = await uni.request({
      url: 'http://localhost:8088/api/mall/goods',
      method: 'GET',
      data: {
        categoryId: activeCategoryId.value,
        page: currentPage,
        pageSize: pagination.value.pageSize
      }
    })
    
    if (data?.code === 200) {
      const response = data.data
      goodsList.value = reset 
        ? response.items 
        : [...goodsList.value, ...response.items]
        
      pagination.value = {
        current: response.currentPage + 1,
        pageSize: response.pageSize,
        total: response.total
      }
      
      loadStatus.value = 
        goodsList.value.length >= response.total 
          ? 'noMore' 
          : 'more'
    }
  } catch (error) {
    console.error('获取商品失败:', error)
    uni.showToast({ title: '商品加载失败', icon: 'none' })
    loadStatus.value = 'more'
  }
}

// 分类切换
const switchCategory = (categoryId) => {
  if (activeCategoryId.value === categoryId) return
  activeCategoryId.value = categoryId
  fetchGoods(true)
}

// 加载更多
const loadMore = () => {
  if (loadStatus.value === 'noMore') return
  fetchGoods()
}

// 计算滚动高度
const calculateHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 50
}

// 生命周期
onMounted(() => {
  calculateHeight()
  fetchCategories()
})

// 跳转方法
const goToSearch = () => {
  uni.navigateTo({ url: '/pages/shop/search' })
}

const goToDetail = (id) => {
  uni.navigateTo({ url: `/pages/shop/detail?id=${id}` })
}
</script>

<style lang="scss" scoped>
/* 原有样式保持不变 */
.page-container {
  background-color: #f5f5f5;
}

.main-content {
  display: flex;
  padding-top: 10rpx;
}

.category-list {
  width: 160rpx;
  background-color: #fff;
  
  .category-item {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    
    &.active {
      color: #e4393c;
      background-color: #f5f5f5;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 40rpx;
        background-color: #e4393c;
      }
    }
  }
}

.goods-list {
  flex: 1;
  padding: 20rpx;
  
  .goods-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }
}
</style>
